#!/usr/bin/env node

/**
 * 验证文档相关三张表结构与样例数据
 */

const { Sequelize } = require('sequelize');

const sequelize = new Sequelize('sso_system', 'root', '12345678', {
  host: 'localhost',
  dialect: 'mysql',
  logging: false,
  timezone: '+08:00'
});

async function main() {
  try {
    await sequelize.authenticate();

    const [tables] = await sequelize.query("SHOW TABLES");
    const tableNames = tables.map(r => Object.values(r)[0]);

    const required = ['documents', 'document_collaborations', 'yjs_documents'];
    const missing = required.filter(t => !tableNames.includes(t));

    if (missing.length) {
      console.error('缺少数据表:', missing);
      process.exitCode = 1;
      return;
    }

    const [[{ cnt: docCount }]] = await sequelize.query('SELECT COUNT(*) AS cnt FROM documents');
    const [[{ cnt: collabCount }]] = await sequelize.query('SELECT COUNT(*) AS cnt FROM document_collaborations');
    const [[{ cnt: yjsCount }]] = await sequelize.query('SELECT COUNT(*) AS cnt FROM yjs_documents');

    const [latestDoc] = await sequelize.query('SELECT id, title, owner_id, status, created_at, updated_at FROM documents ORDER BY created_at DESC LIMIT 1');
    const [latestCollab] = await sequelize.query('SELECT id, document_id, user_id, permission, invited_by, invited_at FROM document_collaborations ORDER BY id DESC LIMIT 1');
    const [latestYjs] = await sequelize.query('SELECT id, document_id, room_name, version, last_updated FROM yjs_documents ORDER BY id DESC LIMIT 1');

    const result = {
      ok: true,
      tables: tableNames,
      counts: { documents: docCount, collaborations: collabCount, yjsDocuments: yjsCount },
      samples: {
        document: latestDoc[0] || null,
        collaboration: latestCollab[0] || null,
        yjsDocument: latestYjs[0] || null
      }
    };

    console.log(JSON.stringify(result, null, 2));
  } catch (err) {
    console.error('验证失败:', err?.message || err);
    process.exitCode = 1;
  } finally {
    await sequelize.close();
  }
}

if (require.main === module) {
  main();
}

module.exports = { main };


